<template>
  <div class="wrapper-tinymce" :class="{ fullscreen: flagFullscreen }" :style="{ width: containerWidth }">
    <vue3-tinymce
      v-model="editorContent"
      :setting="setting"
      script-src="/tinymce/tinymce.min.js"
      @change="changeValue"
    />
    <div class="tinymce-btn-upload">
      <image-uploader class="uploader" @setUploadResult="getUploadResultListImage($event)" />
      <file-uploader class="uploader" @setUploadResult="getUploadResultListFile($event)" />
    </div>
  </div>
</template>

<script>
import Vue3Tinymce from '@jsdawn/vue3-tinymce'
import imageUploader from '@c/UploadImages2Local'
import fileUploader from '@c/UploadFiles2Local'

import { defineComponent, ref, computed, watch, onMounted } from 'vue'
export default defineComponent({
  name: 'Tinymce6Com',
  components: { Vue3Tinymce, imageUploader, fileUploader },
  props: {
    content: {
      type: String,
      default: '',
    },
    width: {
      type: [Number, String],
      required: false,
      default: '100%',
    },
    height: {
      type: [Number, String],
      required: false,
      default: 600,
    },
  },
  emit: ['update:inputContent'],
  setup(props, { emit }) {
    const urlPrefixDownloadFile = ref(process.env.VUE_APP_URL_DOWNLOAD)
    // 设置显示图片的前缀
    const urlRoot = ref(process.env.VUE_APP_URL_UPLOAD_SHOW_UUID)
    // 执行上传到服务器的action的url
    const urlActionRemote = ref(process.env.VUE_APP_URL_UPLOAD_ACTION)
    const flagFullscreen = ref(false)
    const editorContent = ref('')
    const pluginAll = ref(
      'anchor autolink charmap codesample code \
      emoticons fullscreen link image lists \
      media quickbars searchreplace table visualblocks \
      wordcount'
    )
    const plugins = ref(
      'anchor autolink charmap codesample code \
      emoticons fullscreen link image lists \
      media searchreplace table visualblocks wordcount'
    )
    const menubar = ref('file edit insert view format table')
    const toolbarAll = ref(
      'anchor alignleft aligncenter alignright alignjustify \
      backcolor blocks blockquote bold bullist \
      code codesample charmap emoticons forecolor \
      fontsize fullscreen hr image insertdatetime \
      indent italic link media numlist \
      outdent pagebreak preview redo removeformat \
      strikethrough subscript superscript table searchreplace \
      underline undo unlink'
    )
    const toolbar1 = ref([
      'fullscreen undo redo | \
      bold italic underline strikethrough superscript subscript | \
      fontsize forecolor backcolor | \
      alignleft aligncenter alignright alignjustify | \
      numlist bullist | removeformat ',
      'blocks indent outdent | link unlink | image media table | charmap code',
    ])
    const toolbar2 = ref(
      'bold italic underline h1 h2 \
      blockquote codesample numlist bullist link \
      image | removeformat fullscreen'
    )
    const toolbar_quickbar = ref('removeformat | bold italic underline strikethrough | fontsize forecolor backcolor')
    const setting = ref({
      language: 'zh-Hans',
      language_url: '/tinymce/langs/zh-Hans.js',
      height: props.height,
      menubar: false,
      plugins: plugins.value,
      toolbar: toolbar1.value,
      toolbar_mode: 'sliding',
      font_size_formats: '12px 14px 16px 18px',
      link_default_target: '_blank',
      link_title: false,
      nonbreaking_force_tab: true,
      content_style: 'body{font-size: 16px}',
    })
    const setting_classic = ref({
      language: 'zh-Hans',
      language_url: '/tinymce/langs/zh-Hans.js',
      height: props.height,
      toolbar: toolbar1.value,
      toolbar_mode: 'sliding',
      quickbars_selection_toolbar: toolbar_quickbar.value,
      plugins: 'link image media table lists fullscreen quickbars charmap codesample code',
      font_size_formats: '12px 14px 16px 18px',
      link_default_target: '_blank',
      link_title: false,
      nonbreaking_force_tab: true,
    })
    const setting_juejin = ref({
      menubar: false,
      height: 190,
      plugins: 'codesample link image table lists fullscreen',
      toolbar: toolbar2.value,
      toolbar_mode: 'sliding',
      nonbreaking_force_tab: true,
      link_title: false,
      link_default_target: '_blank',
      content_style: 'body{font-size: 16px}',
      // 自定义 图片上传模式
      custom_images_upload: true,
      images_upload_url: 'your_upload_api_url...',
      custom_images_upload_callback: (res) => res.url,
      custom_images_upload_param: { id: 'xxxx01', age: 18 },
    })
    const containerWidth = computed(() => {
      const width = props.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    })

    const changeValue = (val) => {
      // console.log('changeValue val：', val)
      if (typeof val === 'string') {
        emit('inputContent', val)
      }
    }

    // 得到上传多张图片的返回值
    const getUploadResultListImage = (val) => {
      val.forEach((v) => {
        const html =
          '<p style="text-align:center;"> \
          <img alt="" style="height: auto; width: 100%; max-width: 640px;" \
           src="' +
          v +
          '" /></p>'
        editorContent.value += html
      })
    }
    // 得到上传多个文件的返回值
    const getUploadResultListFile = (val) => {
      val.forEach((v) => {
        console.log('v', v)
        let html = '<p><a style="font-size:16px;" target="_blank"'
        html += ' href="' + urlPrefixDownloadFile.value + v.uuid + '">'
        html += '点此下载： ' + v.FileNameClient + '</a></p>'
        editorContent.value += html
      })
    }

    onMounted(() => {
      editorContent.value = props.content
    })

    watch(
      () => props.content,
      (val) => {
        if (typeof val === 'string') {
          // console.log('watch props.content', val)
          editorContent.value = val
        }
      }
    )

    return {
      urlRoot,
      urlActionRemote,
      urlPrefixDownloadFile,
      flagFullscreen,
      containerWidth,
      editorContent,
      pluginAll,
      plugins,
      menubar,
      toolbarAll,
      toolbar1,
      toolbar2,
      toolbar_quickbar,
      setting,
      setting_classic,
      setting_juejin,
      changeValue,
      getUploadResultListImage,
      getUploadResultListFile,
    }
  },
})
</script>

<style lang="scss" scoped>
// 上传内容图片及附件按钮区
.tinymce-btn-upload {
  position: absolute;
  right: 16px;
  top: 6px;
  z-index: 201;
  .uploader {
    float: left;
    margin-left: 8px;
  }
}
.fullscreen .tinymce-btn-upload {
  position: fixed;
}
</style>
